package redis.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.RedisCuckooFilter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.service.CacheService;
import redis.service.model.Item;
import redis.service.repository.ItemRepository;

import java.util.List;

@Service
public class CacheServiceImpl implements CacheService {
    private final RedisCuckooFilter redisCuckooFilter;
    private final JedisPool jedisPool;
    private final ItemRepository itemRepository;

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Autowired
    public CacheServiceImpl(ItemRepository itemRepository) {
        this.redisCuckooFilter = new RedisCuckooFilter(redisHost, redisPort);
        this.jedisPool = new JedisPool(redisHost, redisPort);
        this.itemRepository = itemRepository;
    }

    @Override
    public void initData() {
        List<Item> items = itemRepository.findAll();
        redisCuckooFilter.createFilter("items", items.size());
        for (Item item : items) {
            redisCuckooFilter.addItem("items", item.getName());
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.set(item.getName(), item.getDescription());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getItem(String key) {
        if (!redisCuckooFilter.existsItem("items", key)) {
            return null;
        }
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}